package com.example.chongwushangcheng.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.petshopping.R;
import com.example.chongwushangcheng.model.PetExchangePost;

import java.util.List;

/**
 * 宠物交流列表适配器
 */
public class PetExchangeAdapter extends RecyclerView.Adapter<PetExchangeAdapter.PostViewHolder> {

    private Context context;
    private List<PetExchangePost> postList;
    private OnItemClickListener listener;

    public PetExchangeAdapter(Context context, List<PetExchangePost> postList) {
        this.context = context;
        this.postList = postList;
    }

    @NonNull
    @Override
    public PostViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_pet_exchange, parent, false);
        return new PostViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull PostViewHolder holder, int position) {
        PetExchangePost post = postList.get(position);
        
        // 设置数据
        holder.ivPostImage.setImageResource(post.getImageResId());
        holder.tvPostTitle.setText(post.getTitle());
        holder.tvPostContent.setText(post.getContent());
        holder.tvPostDate.setText(post.getDate());
        holder.tvPostLocation.setText(post.getLocation());
        
        // 设置点击事件
        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onItemClick(position);
            }
        });
    }

    @Override
    public int getItemCount() {
        return postList.size();
    }
    
    // 设置点击监听器
    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }
    
    // 点击监听器接口
    public interface OnItemClickListener {
        void onItemClick(int position);
    }

    static class PostViewHolder extends RecyclerView.ViewHolder {
        ImageView ivPostImage;
        TextView tvPostTitle;
        TextView tvPostContent;
        TextView tvPostDate;
        TextView tvPostLocation;

        public PostViewHolder(@NonNull View itemView) {
            super(itemView);
            ivPostImage = itemView.findViewById(R.id.iv_post_image);
            tvPostTitle = itemView.findViewById(R.id.tv_post_title);
            tvPostContent = itemView.findViewById(R.id.tv_post_content);
            tvPostDate = itemView.findViewById(R.id.tv_post_date);
            tvPostLocation = itemView.findViewById(R.id.tv_post_location);
        }
    }
} 